/* eslint-disable react/destructuring-assignment */
/* eslint-disable no-param-reassign */
/* eslint-disable eqeqeq */
import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Table, Input, Button, Popconfirm, Select, Divider } from 'antd';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const EditableContext = React.createContext();

class EditableCell extends React.Component {
  state = {
    editing: true,
  };

  // 选择字段项目
  selectMat = (value, options, key) => {
    const { datas, changedata, tableid } = this.props;
    // eslint-disable-next-line array-callback-return
    datas.map(item => {
      if (item.key == key) {
        item.matId = value;
        item.colName = options.props.children;
      }
    });
    changedata(datas, tableid);
  };

  // 更改自定义名称
  changeName = (e, key) => {
    const { datas, changedata, tableid } = this.props;
    // eslint-disable-next-line array-callback-return
    datas.map(item => {
      if (item.key == key) {
        item.colCustomName = e.target.value;
      }
    });
    changedata(datas, tableid);
  };

  render() {
    const { editing } = this.state;
    const { editable, dataIndex, title, record, index, projectList, ...restProps } = this.props;
    return (
      // eslint-disable-next-line no-return-assign
      <td ref={node => (this.cell = node)} {...restProps}>
        {editable ? (
          <EditableContext.Consumer>
            {form => {
              this.form = form;
              return editing ? (
                <FormItem>
                  {form.getFieldDecorator(`declDetailCols[${record.key}][${dataIndex}]`, {
                    rules: [
                      {
                        required: dataIndex == 'matId',
                        message: dataIndex == 'matId' ? '请选择' : '请输入',
                      },
                    ],
                    initialValue: record[dataIndex],
                  })(
                    dataIndex == 'matId' ? (
                      <HOCSelect
                        placeholder="请选择"
                        showSearch
                        optionFilterProp="children"
                        style={{ width: 220, margin: '0 64px 0 0' }}
                        notFoundContent="暂无数据"
                        onChange={(value, options) => this.selectMat(value, options, record.key)}
                      >
                        {projectList.map(item => (
                          <Option key={item.matId} value={item.matId}>
                            {item.colName}
                          </Option>
                        ))}
                      </HOCSelect>
                    ) : (
                      <Input
                        // eslint-disable-next-line no-return-assign
                        ref={node => (this.input = node)}
                        placeholder="请输入自定义名称"
                        style={{ margin: '0 64px 0 0' }}
                        maxLength={20}
                        onChange={e => this.changeName(e, record.key)}
                      />
                    )
                  )}
                </FormItem>
              ) : (
                <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }}>
                  {restProps.children}
                </div>
              );
            }}
          </EditableContext.Consumer>
        ) : (
          restProps.children
        )}
      </td>
    );
  }
}

// eslint-disable-next-line react/no-multi-comp
class TableForm extends React.Component {
  // eslint-disable-next-line react/sort-comp
  EditableFormRow = ({ ...props }) => (
    <EditableContext.Provider value={this.props.form}>
      <tr {...props} />
    </EditableContext.Provider>
  );

  columns = [
    {
      title: '字段名称',
      dataIndex: 'matId',
      width: '30%',
      editable: true,
    },
    {
      title: '自定义名称',
      dataIndex: 'colCustomName',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      onHeaderCell: () =>
        this.props.datas.length === 1 ? { style: { opacity: '0' } } : { style: { opacity: '1' } },
      onCell: () =>
        this.props.datas.length === 1 ? { style: { opacity: '0' } } : { style: { opacity: '1' } },
      render: (text, record, index) => (
        <span style={{ position: 'relative', top: '-12px' }}>
          {index > 0 && (
            <Popconfirm title="您确定要删除此行吗?" onConfirm={() => this.delete(record.key)}>
              <a>删除</a>
            </Popconfirm>
          )}
          {index > 0 ? <Divider type="vertical" /> : null}
          {index > 0 ? <a onClick={() => this.handleMove(record.key, 1)}>上移</a> : null}
          {this.props.datas.length > index + 1 && index > 0 ? <Divider type="vertical" /> : null}
          {this.props.datas.length > index + 1 ? (
            <a onClick={() => this.handleMove(record.key, 0)}>下移</a>
          ) : null}
        </span>
      ),
    },
  ];

  // 添加行
  add = () => {
    const { datas, changeDataSource } = this.props;
    let { tableId } = this.props;
    tableId += 1;
    const newData = {
      key: tableId,
      matId: undefined,
      colName: undefined,
      colCustomName: undefined,
    };
    changeDataSource([...datas, newData], tableId);
  };

  // 删除行
  delete = key => {
    const { datas, changeDataSource, tableId } = this.props;
    changeDataSource(datas.filter(item => item.key !== key), tableId);
  };

  // 移动行
  handleMove(key, dir) {
    const {
      datas,
      onMove,
      form: { setFieldsValue },
    } = this.props;
    datas.some((val, index) => {
      if (val.key === key) {
        // eslint-disable-next-line no-empty
        if (dir === 1 && index === 0) {
          // eslint-disable-next-line no-empty
        } else if (dir === 0 && index === datas.length - 1) {
        } else {
          const nextIndex = dir === 1 ? index - 1 : index + 1;
          onMove(index, nextIndex);
          setFieldsValue({
            [`declDetailCols[${datas[nextIndex].key}][matId]`]: datas[nextIndex].matId,
            [`declDetailCols[${datas[nextIndex].key}][colCustomName]`]: datas[nextIndex]
              .colCustomName,
            [`declDetailCols[${key}][matId]`]: val.matId,
            [`declDetailCols[${key}][colCustomName]`]: val.colCustomName,
          });
        }
        return true;
      }
      return false;
    });
  }

  render() {
    const { projectList, datas, changeDataSource, tableId } = this.props;
    const components = {
      body: {
        row: this.EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record, index) => ({
          record,
          index,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          projectList,
          datas,
          changedata: changeDataSource,
          tableid: tableId,
        }),
      };
    });
    return (
      <div style={{ width: 800 }}>
        <Table
          pagination={false}
          components={components}
          rowKey="key"
          dataSource={datas}
          columns={columns}
          className={styles.rowPadding}
        />
        <Button
          icon={<PlusOutlined />}
          style={{ width: '100%', marginTop: 16, border: '1px dashed #ccc' }}
          onClick={this.add}
        >
          添加申报明细表字段
        </Button>
      </div>
    );
  }
}
export default TableForm;
